#include "widget.h"
#include <QApplication>

int pipe_fd[2];

typedef struct thpid{
    int pid_1;
    int pid_2;
}THPID;

int main(int argc, char *argv[])
{
    pipe(pipe_fd);
    mkfifo("fifo",0666);


    key_t key= ftok(".", 1314);
    int Tid = shmget(key, 500, IPC_CREAT | 0777);
    THPID *THpid= (THPID *)shmat(Tid, NULL, 0);

    pid_t pid;
    int i=0;
    for(;i<2;i++)
    {
        pid=fork();
        if(pid==0)
        {
            break;
        }
    }
    if(i==0)
    {
        THpid->pid_1=getpid();
        dup2(pipe_fd[1],1);
        execlp("mplayer", "mplayer", "-slave","-quiet","-idle","-input", "file=./fifo","../mp3player/song/简单爱.mp3",NULL);
    }
    if(i==1)
    {
        THpid->pid_2=getpid();

        QApplication a(argc, argv);
        Widget w(pipe_fd[0]);
        w.show();
        return a.exec();
    }
    if(i==2)
    {
        while(1)
        {
            int ret= waitpid(-1,NULL,WNOHANG);
            if (ret==0)
            {
                continue;
            }
            else if (ret>0)
            {
                if(ret==THpid->pid_2)
                {
                    kill(THpid->pid_1,9);
                }
            }
            else
            {
                break;
            }
        }
    }

}
